lapis = require "lapis"
import respond_to from require "lapis.application"
import Model from require "lapis.db.model"

class User extends Model
    @table_name:=> "users"

class UserApplication extends lapis.Application

    [user_list:"/user/list"]: respond_to{
        GET: =>
            @users = User\select!
            render:"user_list"
    }

    [user_delete: "/user/delete/:id"]: respond_to {
        before: =>
            @user = User\find @params.id
            @write status: 404, "Not Found" unless @user
        GET: =>
            render: true
        POST: =>
            @user\delete!
            @users = User\select!
            render:"user_list"
    }

    [user_edit: "/user/edit/:id"]: respond_to {
        before: =>
            @user = User\find @params.id
            @write status: 404, "Not Found" unless @user

        GET: =>
            render: true

        POST: =>
            @user\update{
                name: @params.name
                sex: @params.sex
                profession: @params.profession
                age: @params.age
                habits: @params.habits
                page: @params.page
                study: @params.study
                note: @params.note
            }
            @users = User\select!
            render:"user_list"
    }

    [user_login:"/user/login"]: respond_to {
        
        GET: =>
            render: true
            
        POST: =>
            user = User\create{
                name: @params.name
                sex: @params.sex
                profession: @params.profession
                age: @params.age
                habits: @params.habits
                page: @params.page
                study: @params.study
                note: @params.note
            }
            @users = User\select!
            render: "user_list"
    }
        
    [user_forget_password:"/user/forget_password"]: =>
        render: true
        
    [user_deleteall:"/user/deleteall"]: respond_to {
        POST: =>
            @users = User\select!
            for i,user in ipairs(@users)
                user\delete!
            render: "user_list"
    }

